// Time:  O(n)
// Space: O(1)

#include <vector>

using namespace std;
class Solution {
public:
    int maxRepOpt1(string text)
    {
        if (text.empty()) return 0;
        
        vector<int> freq(26, 0);
        for (char c : text) {
            freq[c - 'a']++;
        }
        
        int maxLen = 0;
        for (char ch = 'a'; ch <= 'z'; ++ch) {
            if (freq[ch - 'a'] == 0) continue;
            
            int left = 0, gap = 0;
            for (int right = 0; right < text.size(); ++right) {
                gap += (text[right] != ch);
                
                while (gap > 1) {
                    gap -= (text[left++] != ch);
                }
                
                maxLen = max(maxLen, 
                    min(right - left + 1, freq[ch - 'a']));
            }
        }
        return maxLen;
    }
};
